package com.fingard.dsp.bank.directbank.psbc11.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;

public class SecurityHelper
{
  public static synchronized String generateMackey(String filePath)
  {
    String mac = null;
    File file = new File(filePath);
    long filelen = 0L;
    FileInputStream fileinputstream = null;
    byte[] filebytes = (byte[])null;
    if (file != null) {
      if (file.canRead())
      {
        filelen = file.length();
        try
        {
          filebytes = new byte[(int)filelen];
          fileinputstream = new FileInputStream(filePath);
          fileinputstream.read(filebytes);
        }
        catch (FileNotFoundException fnfe)
        {
          System.out.println("文件未找到");
          fnfe.printStackTrace();
        }
        catch (IOException ie)
        {
          System.out.println("IO异常");
          ie.printStackTrace();
        }
        try
        {
          MessageDigest md = MessageDigest.getInstance("SHA1");
          md.update(filebytes);
          byte[] bytes = md.digest();
          mac = new SecurityHelper().format(bytes);
          md.reset();
        }
        catch (Exception e)
        {
          System.out.println("使用SHA1算法计算信息摘要出现异常，追踪输出如下：");
          e.printStackTrace();
        }
      }
      else
      {
        System.out.println("文件不可读");
        return null;
      }
    }
    return mac;
  }
  
  private String format(byte[] bytes)
  {
    String to16Str = new String();
    for (int i = 0; i < bytes.length; i++)
    {
      byte onetype = bytes[i];
      
      char tmpChar = (char)(onetype >>> 4 & 0xF);
      char high4bits;
//      char high4bits;
      if (tmpChar >= '\n') {
        high4bits = (char)('A' + tmpChar - 10);
      } else {
        high4bits = (char)('0' + tmpChar);
      }
      to16Str = to16Str + high4bits;
      
      tmpChar = (char)(onetype & 0xF);
      char low4bits;
//      char low4bits;
      if (tmpChar >= '\n') {
        low4bits = (char)('A' + tmpChar - 10);
      } else {
        low4bits = (char)('0' + tmpChar);
      }
      to16Str = to16Str + low4bits;
    }
    return to16Str;
  }
  
  public static void main(String[] args)
  {
    String newmac = generateMackey("yyycore");
    System.out.println("信息摘要[" + newmac + "]");
  }
}
